<!--玩家详情-->
<template>
    <div class="app-container">
      <h1>  ID： {{ player.playerId }}   {{ player.nickname }}  </h1>
      <h3 v-if="boundWxData"  style="display: flex; align-items: center;">
        关联的微信：{{ boundWxData.wxId }} {{ boundWxData.wxName }}
        <el-button type="danger" size="small" @click="unbindWx" style="margin-left: 20px; width: 80px;">解绑</el-button>
      </h3>
      <h3 v-else>
        未关联微信
      </h3>
      <div style="border-radius: 10px; background-color: #FFFFFF; padding: 20px; border: 1px solid #EEEEEE; margin-top: 40px;">
      <h1>玩家报表</h1>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="true" label-width="68px">
          <el-form-item label="">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="getRangeDataReport">筛选</el-button>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="get30DaysDataReport">近30天</el-button>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="getDataReport">全部</el-button>
          </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="dataReport">
          <el-table-column
            label="总手数"
            align="center"
            prop="totalHands"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="总保险"
            align="center"
            prop="totalInsurancePool"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="总活跃度积分"
            align="center"
            prop="totalActivityPoints"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="总战绩"
            align="center"
            prop="totalScore"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="总JP贡献值"
            align="center"
            prop="totalJpContribution"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="总带入"
            align="center"
            prop="totalBuyIn"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="总战绩流水"
            align="center"
            prop="totalScoreDetails"
            :show-overflow-tooltip="true"
          />
      </el-table>
      </div>

      <div style="border-radius: 10px; background-color: #FFFFFF; padding: 20px; border: 1px solid #EEEEEE; margin-top: 40px;">
      <el-row type="flex" justify="space-between" align="middle">
          <h1>局内数据</h1>
          <el-button type="primary" icon="el-icon-plus" @click="playDataAction(1)">添加数据</el-button>
      </el-row>

      <el-table v-loading="dataLoading" :data="tableData">
        <el-table-column
          label="俱乐部ID"
          align="center"
          prop="clubId"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="俱乐部名称"
          align="center"
          prop="clubName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="房间号"
          align="center"
          prop="roomNumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="房间名称"
          align="center"
          prop="roomName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
                label="是否开启保险"
                align="center"
                prop="insuranceEnabled"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="保险池"
                align="center"
                prop="insurancePool"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="综活跃积分"
                align="center"
                prop="totalActivityPoints"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="JP贡献值"
                align="center"
                prop="jpContribution"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="带入"
                align="center"
                prop="buyIn"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="盲注级别"
                align="center"
                prop="blindLevel"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="手数"
                align="center"
                prop="hands"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="战绩"
                align="center"
                prop="score"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="战绩流水"
                align="center"
                prop="scoreDetails"
                :show-overflow-tooltip="true"
              />
        <el-table-column
                label="结束时间"
                align="center"
                prop="displayedEndTime"
                :show-overflow-tooltip="true"
              />
        <el-table-column label="操作" align="center" >
          <template slot-scope="scope">
           <el-button
               size="mini"
               type="text"
               @click="playDataAction(3, scope.row)">修改</el-button>

            <el-button
              size="mini"
              type="text"
              @click="playDataAction(2, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getPlayData"/>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="640px" center>
        <el-form ref="playDataForm" :rules="playDataRules" :model="playDataForm" label-width="120px">
              <el-form-item label="俱乐部Id" prop="clubId">
                <el-input placeholder="请输入俱乐部Id" v-model.number="playDataForm.clubId"> </el-input>
              </el-form-item>
              <el-form-item label="俱乐部名称"  prop="clubName">
                <el-input placeholder="请输入俱乐部名称" v-model="playDataForm.clubName" />
              </el-form-item>
              <el-form-item label="房间号" prop="roomNumber" >
                <el-input placeholder="请输入房间号" v-model.number="playDataForm.roomNumber" />
              </el-form-item>
              <el-form-item label="房间名称" prop="roomName">
                <el-input placeholder="请输入房间名称" v-model="playDataForm.roomName" />
              </el-form-item>
              <el-form-item label="是否开启保险池" >
                <el-input placeholder="是否开启保险池" v-model.number="playDataForm.insuranceEnabled" />
              </el-form-item>
              <el-form-item label="保险池">
                <el-input placeholder="保险池" v-model.number="playDataForm.insurancePool" />
              </el-form-item>
              <el-form-item label="总活跃积分" >
                <el-input placeholder="总活跃积分" v-model.number="playDataForm.totalActivityPoints" />
              </el-form-item>
              <el-form-item label="JP贡献值">
                <el-input placeholder="JP贡献值" v-model.number="playDataForm.jpContribution" />
              </el-form-item>
              <el-form-item label="昵称" prop="nickname">
                <el-input placeholder="昵称" v-model="playDataForm.nickname" />
              </el-form-item>
              <el-form-item label="备注名">
                <el-input placeholder="备注名" v-model="playDataForm.remarkName" />
              </el-form-item>
              <el-form-item label="用户ID" prop="playerId">
                <el-input placeholder="用户ID" v-model.number="playDataForm.playerId" />
              </el-form-item>
              <el-form-item label="带入" prop="buyIn">
                <el-input placeholder="带入" v-model.number="playDataForm.buyIn" />
              </el-form-item>
              <el-form-item label="盲注级别" prop="blindLevel">
                <el-input placeholder="盲注级别（Example: 2/4）" v-model="playDataForm.blindLevel" />
              </el-form-item>
               <el-form-item label="手数" prop="hands">
                 <el-input placeholder="手数" v-model.number="playDataForm.hands" />
               </el-form-item>
              <el-form-item label="战绩" prop="score">
                <el-input placeholder="战绩" v-model.number="playDataForm.score" />
              </el-form-item>
              <el-form-item label="战绩流水" prop="scoreDetails">
                <el-input placeholder="战绩流水" v-model.number="playDataForm.scoreDetails" />
              </el-form-item>
               <el-form-item label="结束时间" prop="displayedEndTime">
                 <el-input placeholder="格式：2024-03-17 11:00:00" v-model="playDataForm.displayedEndTime"/>
               </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddOrUpdate('playDataForm')">{{ playDataForm.id == -1 ? '新 增' : '修 改' }}</el-button>
        </span>
      </el-dialog>
       </div>
    </div>
</template>
<script>

import {
  getPlayerInfo,
  bindOrUnbindWx,
} from "@/api/account/player.js";
import {
  getPlayDataByPlayer,
  addOrUpdatePlayData,
} from "@/api/data/playData.js";
import { getWxInfo, } from "@/api/account/wx.js";
import { getDataReport, } from "@/api/data/report.js";
import {
  goSearchWeChat,
  bindWxAndPlayer,
  unbindWxAndPlayer,
} from "@/api/account/wx.js";

export default {
  data(){
    return{
       player: {
          id:0,
          playerId: 0,
          nickname: "",
          refPlayerWxId: null,
       },
       queryParams: {
          playerId: undefined,
          dateRange: [],
       },
       loading: false,
       dataReport: [],
       dateRange: [],
       form: {
               totalHands: 0,
               totalInsurancePool: 0,
               totalActivityPoints: 0,
               totalScore: 0,
               totalJpContribution: 0,
               totalBuyIn: 0,
               totalScoreDetails: 0,
             },
       wxParams: {
          playerId: undefined,
          wxId: undefined,
       },
      boundWxLoading: false,
      boundWxData: null,

      total:0,
      dataLoading: false,
      tableData:[],

      dialogTitle:"",
      dialogVisible: false,
      playDataForm: {
        id: -1,
        clubId: "",
        clubName: "",
        roomNumber: "",
        roomName: "",
        insuranceEnabled: 0,
        insurancePool: 0,
        totalActivityPoints:0,
        jpContribution: 0,
        nickname:"",
        remarkName:"",
        playerId:0,
        buyIn:0,
        blindLevel:"",
        hands:0,
        score:0,
        scoreDetails:0,
        displayedEndTime: this.getCurrentTime(),
      },
      playDataRules: {
        clubId: [{ required: true, message: "请输入俱乐部id", trigger: "blur" }],
        clubName: [{ required: true, message: "请输入俱乐部名称", trigger: "blur" }],
        roomNumber: [{ required: true, message: "请输入房号", trigger: "blur" }],
        roomName: [{ required: true, message: "请输入房间名称", trigger: "blur" }],
        playerId: [{ required: true, message: "请输入玩家id", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入玩家名称", trigger: "blur" }],
        buyIn: [{ required: true, message: "请输入带入", trigger: "blur" }],
        blindLevel: [{ required: true, message: "请输入盲注级别", trigger: "blur" }],
        hands: [{ required: true, message: "请输入手数", trigger: "blur" }],
        score: [{ required: true, message: "请输入盲战绩", trigger: "blur" }],
        scoreDetails: [{ required: true, message: "请输入战绩流水", trigger: "blur" }],
        displayedEndTime: [{ required: true, message: "格式：2024-03-17 11:00:00", trigger: "displayedEndTime" }],
      },
    }
  },
  mounted(){
    this.getPlayerInfo()
    this.getDataReport()
    this.getPlayData()
  },
  methods:{
    // 查看用户详情
    getPlayerInfo(){
      let params={
        playerId:this.$route.query.id
      }
      getPlayerInfo(params).then(res=>{
        console.info("getPlayerInfo ", res.data)
        this.player = res.data

        this.getBoundWx()
      }).catch((error) => {
        // 处理接口异常
        console.error("getPlayerInfo err : ", error)
        goBack()
      });
    },

    // 玩家关联微信 ： 一个玩家只会绑定一个微信
    getBoundWx() {
      if (this.player.refPlayerWxId != undefined) {
        let params = {
          id: this.player.refPlayerWxId,
        };
        console.info("getBoundWx id :", params.id)
        this.boundWxLoading = true
        getWxInfo(params).then((res) => {
          this.boundWxData = res.data
          this.boundWxLoading = false
          console.info("getBoundWx success:", this.boundWxData);
        }).catch((error) => {
          // 处理接口异常
          console.error("getBoundWx error:", error);
          this.boundWxData = null
          this.boundWxLoading = false
        });
      }

    },

    getPlayData(){
      let params={
        playerId:this.$route.query.id
      }
      this.dataLoading = true;
      getPlayDataByPlayer(params).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.dataLoading = false;
        console.info("getPlayData success:", this.total);
      }).catch((error) => {
        // 处理接口异常
        console.error("getPlayData error:", error);
        this.dataLoading = false;
      });
    },

    // 查询数据列表
    getDataReport() {
      this.loading = true;
      let params={
         playerId: this.$route.query.id
      }
      getDataReport(params).then((res) => {
        this.dataReport = [res.report]
        this.loading = false
      }).catch((error) => {
        // 处理接口异常
        this.dataReport = []
        this.loading = false;
      });
    },

    // 查询数据列表
    get30DaysDataReport() {
      this.loading = true;
      // 计算从昨天结束的最近 30 天时间范围
      const today = new Date();
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
      const startDate = this.formatDate(new Date(yesterday.getTime() - 29 * 24 * 60 * 60 * 1000));
      const endDate = this.formatDate(yesterday);
      let params = {
        playerId: this.$route.query.id,
        startDate: startDate,
        endDate: endDate
      };
      getDataReport(params).then((res) => {
        this.dataReport = [res.report]
        this.loading = false
      }).catch((error) => {
        // 处理接口异常
        this.dataReport = []
        this.loading = false;
      });
    },
    // 查询数据列表
    getRangeDataReport() {
       if (!this.dateRange[0] || this.dateRange[0] === undefined || !this.dateRange[1] || this.dateRange[1] === undefined) {
          // 显示提示信息
          console.error("请输入时间范围");
          return;
      }
      this.loading = true;
      // 计算范围时间的数据报表
      let params = {
        playerId: this.$route.query.id,
        startDate: this.dateRange[0],
        endDate: this.dateRange[1],
      };
      getDataReport(params).then((res) => {
        this.dataReport = [res.report]
        this.loading = false
      }).catch((error) => {
        // 处理接口异常
        // console.error("getRangeDataReport error:", error);
        this.dataReport = []
        this.loading = false;
      });
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 取消关联
    unbindWx() {
       console.info("unbindWx :", this.player)
       this.player.refPlayerWxId = null
       bindOrUnbindWx(this.player).then((res) => {
          console.info("unbindWx ", res);
          this.boundWxData = null
       }).catch((error) => {
          console.error("unbindWx error:", error);
       });
    },

    // 操作
    playDataAction(type, row) {
      console.info("playDataAction type:", type, row);
      switch (type) {
        case 1:
          // 增
          this.dialogTitle = "添加数据";
          this.playDataForm = {
              id: -1,
              clubId: "",
              clubName: "",
              roomNumber: "",
              roomName: "",
              insuranceEnabled: 0,
              insurancePool: 0,
              totalActivityPoints:0,
              jpContribution: 0,
              nickname: this.player.nickname,
              remarkName: this.player.remarkName,
              playerId: this.player.playerId,
              buyIn:0,
              blindLevel:"",
              hands:0,
              score:0,
              scoreDetails:0,
              displayedEndTime: this.getCurrentTime(),
            };
          this.dialogVisible = true;
          break;
        case 2:
          this.playDataForm  = { ...row };
          this.$confirm("确定要删除" + row.nickname + "在" + row.clubName +"的一条记录吗？", "提示", {
            type: "warning",
          }).then(() => {
            console.error("deletePlayData params:", params.id);
            deletePlayData(this.playDataForm).then((res) => {
              getPlayData();
            }).catch((error) => {
              // 处理接口异常
              console.error("addOrUpdate error:", error);
              this.dataLoading = false;
            });
          });
          break;
        case 3:
          // 修改
          this.playDataForm  = { ...row };
          this.dialogTitle = "修改数据";
          this.dialogVisible = true;
          break;
      }
    },
    // 提交
    handleAddOrUpdate(form){
      if (this.isValidDateTimeFormat(this.playDataForm.displayedEndTime)){
        // 提交新增或修改
        addOrUpdatePlayData(this.playDataForm).then((res) => {
          this.isNew = false;
          this.dialogVisible = false;

          // 添加后更新列表
          getPlayData();
        }).catch((error) => {
          // 处理接口异常
          console.error("handleAddOrUpdate error:", error);
          this.loading = false;
        });
      } else {
        // 弹出 Toast 提示时间格式不正确
        console.error("时间格式不正确");
        this.$alert('时间格式不正确, 请输入正确的 "yyyy-MM-dd HH:mm:ss" 格式', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                // 用户确认后的回调
              }
            });
      }
    },
    isValidDateTimeFormat(dateTimeString) {
      const dateTimeRegex = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
      return dateTimeRegex.test(dateTimeString);
    },
    getCurrentTime() {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 返回上一页
    goBack(){
      this.$router.go(-1);
    },
  }
}
</script>
